package com.demo.minademo;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.HandlerThread;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class MinaService extends Service {

    private ConnectionThread thread;
    @Override
    public void onCreate() {
        super.onCreate();
        thread = new ConnectionThread(getApplicationContext(),"mina");
        thread.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        thread.disConnect();
        thread = null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    class ConnectionThread extends HandlerThread{

        private Context context;
        boolean isConnection;
        ConnectionManager manager;
        public ConnectionThread(Context context, String name) {
            super(name);
            this.context = context;
            ConnectionConfig config = new ConnectionConfig.Builder(context)
                    .setIp("192.168.1.100")
                    .setPort(9022)
                    .setReadBufferSize(10240)
                    .setConnectionTimeout(10000)
                    .builder();
            manager = new ConnectionManager(config);
        }

        @Override
        protected void onLooperPrepared() {
            super.onLooperPrepared();
            while (true){
                isConnection = manager.connect();
                if(isConnection){
                    Log.e("mina","连接成功！");
                    break;
                }

                try {
                    Thread.sleep(3000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        public void disConnect(){
            manager.disConnect();
        }
    }
}
